"""
账号检测功能
"""
from typing import Dict, Any, Tuple
from enum import Enum
import logging
from com.db.order_account_manager import OrderAccountManager
from com.db.scan_account_manager import ScanAccountManager
from reqapi.token_verify_api import TokenVerifyApi
from reqapi.models.token_verify import TokenVerifyRequest

# 配置日志
logger = logging.getLogger(__name__)

class AccountType(Enum):
    """账号类型"""
    SCAN = 1  # 扫货账号
    ORDER = 2  # 下单账号

class AccountChecker:
    """账号检测器"""
    
    def __init__(self):
        """初始化账号检测器"""
        # 不在初始化时创建BatchSellOrderApi实例，而是在需要时创建
        self.order_account_manager = OrderAccountManager()
        self.scan_account_manager = ScanAccountManager()
        
    def check_account(self, account_id: int, account_type: AccountType) -> Tuple[bool, str, Dict[str, Any]]:
        """检测账号
        
        Args:
            account_id: 账号ID
            account_type: 账号类型
            
        Returns:
            Tuple[bool, str, Dict[str, Any]]:
            - 是否成功
            - 提示信息
            - 账号信息（成功时返回）
        """
        try:
            # 获取账号信息
            if account_type == AccountType.SCAN:
                account = self.scan_account_manager.get_account_by_id(account_id)
                if not account:
                    return False, "未找到扫货账号", None
                
                logger.info(f"扫货账号信息: {account}")
                
                # 获取token和其他必要信息
                # 兼容字典和对象两种情况
                if isinstance(account, dict):
                    token = account.get('uu_token', '')
                    device_id = account.get('device_id', '')
                    uk = account.get('uk', '')
                    account_name = account.get('name', f'扫货账号{account_id}')
                else:
                    token = getattr(account, 'uu_token', '')
                    device_id = getattr(account, 'device_id', '')
                    uk = getattr(account, 'uk', '')
                    account_name = getattr(account, 'name', f'扫货账号{account_id}')
                
                logger.info(f"扫货账号参数: token={token}, device_id={device_id}, uk={uk}")
                
                if not token or not device_id or not uk:
                    return False, f"账号信息不完整，缺少token、device_id或uk: token={token}, device_id={device_id}, uk={uk}", None
            
            else:  # 下单账号
                account = self.order_account_manager.get_account_by_id(account_id)
                if not account:
                    return False, "未找到下单账号", None
                
                logger.info(f"下单账号信息: {account}")
                
                # 获取token和其他必要信息
                # 兼容字典和对象两种情况
                if isinstance(account, dict):
                    token = account.get('uu_token', '')
                    device_id = account.get('device_id', '')
                    uk = account.get('uk', '')
                    account_name = account.get('name', f'下单账号{account_id}')
                else:
                    token = getattr(account, 'uu_token', '')
                    device_id = getattr(account, 'device_id', '')
                    uk = getattr(account, 'uk', '')
                    account_name = getattr(account, 'name', f'下单账号{account_id}')
                
                logger.info(f"下单账号参数: token={token}, device_id={device_id}, uk={uk}")
                
                if not token or not device_id or not uk:
                    return False, f"账号信息不完整，缺少token、device_id或uk: token={token}, device_id={device_id}, uk={uk}", None
            
            # 调用TokenVerifyApi判断token有效性
            api = TokenVerifyApi(device_id=device_id, uk=uk, auth_token=token, device_token=token)
            verify_req = TokenVerifyRequest(token=token, Sessionid=device_id)
            verify_resp = api.verify_token(verify_req)
            # 校验token响应，需严格判断data.result为True才算有效
            if verify_resp is None or getattr(verify_resp, 'code', -1) != 0:
                msg = getattr(verify_resp, 'msg', 'Token无效') if verify_resp else 'Token无效'
                return False, f"账号【{account_name}】无效: {msg}", None
            # 进一步判断data.result
            if not (hasattr(verify_resp, 'data') and verify_resp.data and getattr(verify_resp.data, 'result', False)):
                msg = getattr(verify_resp.data, 'msg', 'Token无效') if (hasattr(verify_resp, 'data') and verify_resp.data) else 'Token无效'
                return False, f"账号【{account_name}】无效: {msg}", None
            # Token校验通过后，直接更新账号状态，无需再调用下单接口
            if account_type == AccountType.SCAN:
                
                # 新增：调用商品列表接口，检查接口有效性
                try:
                    from reqapi.get_commodity_list import GetCommodityListApi
                    user_id = account.get('uu_user_id', '') if isinstance(account, dict) else getattr(account, 'uu_user_id', '')
                    
                    api = GetCommodityListApi(device_token=device_id, device_id=device_id, auth_token=token, uk=uk, user_id=user_id)
                    resp = api.execute(template_id=102423,max_price=0.01,min_abrade=0.15,max_abrade=0.18,page_size=1)
                    # 支持dict或对象，同时处理大写和小写字段名
                    code = None
                    msg = None
                    if isinstance(resp, dict):
                        # 尝试获取大写或小写的code字段
                        code = resp.get('Code', resp.get('code'))
                        # 尝试获取大写或小写的msg/message字段
                        msg = resp.get('Msg', resp.get('msg', resp.get('message', str(resp))))
                    else:
                        # 尝试获取对象的大写或小写属性
                        code = getattr(resp, 'Code', getattr(resp, 'code', None))
                        msg = getattr(resp, 'Msg', getattr(resp, 'msg', getattr(resp, 'message', str(resp))))
                    
                    if code != 0:
                        return False, f"扫货账号【{account_name}】登录状态校验正常，扫货校验异常: {msg}", None
                except Exception as e:
                    return False, f"扫货账号【{account_name}】登录状态校验正常，扫货校验失败: {str(e)}", None
                
                # 更新账号状态
                self.scan_account_manager.update_uu_alive(account_id, 1)
            else:
                # 新增：调用批量下单接口，检查账号有效性
                try:
                    from reqapi.batch_sell_api import BatchSellOrderApi, BatchSellOrderRequest, CommodityItem
                    # 获取必要参数
                    user_id = account.get('uu_user_id', '') if isinstance(account, dict) else getattr(account, 'uu_user_id', '')
                    device_id = account.get('device_id', '') if isinstance(account, dict) else getattr(account, 'device_id', '')
                    token = account.get('uu_token', '') if isinstance(account, dict) else getattr(account, 'uu_token', '')
                    uk = account.get('uk', '') if isinstance(account, dict) else getattr(account, 'uk', '')
                    # 构造API实例
                    api = BatchSellOrderApi(device_token=device_id, device_id=device_id, auth_token=token, uk=uk)
                    # 构造最小商品列表和请求
                    commodity_list = [CommodityItem(commodityId=1257926550, commodityIdPrice="0.01", templateId=102423)]
                    request = BatchSellOrderRequest(
                        buyNumber=1,
                        commodityList=commodity_list,
                        orderSubType=9,
                        paySellAmount="0.01",
                        templateId=102423,
                        unitPrice="0.01",
                        Sessionid=device_id
                    )
                    resp = api.create_batch_order(request)
                    # 响应码判断
                    if resp is None:
                        return False, f"下单账号【{account_name}】登录状态校验正常，下单校验失败: 批量下单接口无响应或异常", None
                    # 支持对象和dict两种情况
                    code = getattr(resp, 'code', None)
                    msg = getattr(resp, 'msg', str(resp))
                    if code is not None and code not in (0, 10001):
                        return False, f"下单账号【{account_name}】登录状态校验正常，下单校验异常: {msg}", None
                except Exception as e:
                    return False, f"下单账号【{account_name}】登录状态校验正常，下单校验异常: {str(e)}", None
                # 更新账号状态
                self.order_account_manager.update_account_status(account_id, status=1)
            # 返回结构与原来一致：True, 提示, account
            return True, f"检测成功，账号【{account_name}】有效", account
            
        except Exception as e:
            logger.error(f"检测账号时发生错误: {str(e)}")
            return False, f"检测账号时发生错误: {str(e)}", None
